package tehMod;

import tehUtils.BlockInstance;
import tehUtils.BlockFinder;

import net.minecraft.src.AxisAlignedBB;
import net.minecraft.src.Block;
import net.minecraft.src.EntityAIPublic;
import net.minecraft.src.ItemStack;

public class VillagerAIGather extends EntityAIPublic {
	public EntityTehVillager villager;
	public BlockInstance targetBlock;
	public long breakTime = -1;
	
	public VillagerAIGather(EntityTehVillager villager) {
		super();
		this.villager = villager;
	}

	@Override
	public boolean shouldExecute() {
		if (!villager.taskGathering)
			return false;
		
		if (targetBlock == null)
			return true;
		
		for (ItemStack item : targetBlock.getBlockDropped(0)) {
			if (!villager.inventory.hasRoomForItem(item)) {
				villager.taskGathering = false;
				villager.taskReturning = true;
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	public void updateTask() {
		super.updateTask();
		
		if (targetBlock == null) {
			AxisAlignedBB searchArea = AxisAlignedBB.getBoundingBox(villager.posX + 6, villager.posY - 2, villager.posZ + 6,
																	villager.posX - 6, villager.posY + 2, villager.posZ - 6);
			targetBlock = BlockFinder.getClosestBlock(searchArea, new int[] {Block.dirt.blockID, Block.grass.blockID});
			villager.setWaypoint(targetBlock.posX, targetBlock.posY, targetBlock.posZ);
		} else {
			if (villager.doneWalking()) {
				long now = System.currentTimeMillis();
				villager.isSwinging = (now < breakTime);
				if (breakTime == -1) {
					villager.faceEntity(villager.waypoint, 1.0f, 1.0f);
					breakTime = now + (long)((targetBlock.block.getHardness() / villager.inventory.getStrVsBlock(targetBlock.block)) * 9000);
				} else if (now > breakTime) {
					villager.faceEntity(villager.waypoint, 1.0f, 1.0f);
					villager.breakBlock(targetBlock);
					targetBlock = null;
					breakTime = -1;
				}
			}
		}
		
	}

}
